package com.bsoft.service.impl;

import com.bsoft.Exception.CommonException;
import com.bsoft.aop.annotation.MultiDataSourceTransactional;
import com.bsoft.mapper.business.CcisMapper;
import com.bsoft.mapper.business.EcgMapper;
import com.bsoft.service.CcisService;
import com.bsoft.service.EcgService;
import com.bsoft.utils.ConmonUtil;
import com.bsoft.utils.XmlMapUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.dom4j.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.sql.Clob;
import java.util.*;

@Service
@EnableTransactionManagement
public class CcisServiceImpl extends ConmonUtil implements CcisService {
    private static Logger logger = LoggerFactory.getLogger(CcisServiceImpl.class);

    @Resource
    private CcisMapper ccisMapper;


    /**
     * 4.2.1获取指定病区的患者ID列表
     */
    @Override
    public String getPatientIdByWard(Map<String, Object> reqMap) throws Exception {
        isNUll(reqMap, "para");
        Map<String, Object> parmMap = (Map<String, Object>) reqMap.get("para");
        List<Map<String, Object>> patientList = ccisMapper.getPatientIdByWard(parmMap);

        Map<String, Object> resMap = new HashMap<>();
        Map<String, Object> patient = new HashMap<>();

        patient.put("patient", patientList);
        resMap.put("patientList", patient);
        resMap.put("status", 200);
        resMap.put("msg", "成功");

        return XmlMapUtils.formatXml(XmlMapUtils.map2xml(resMap, "response"));
    }

    /**
     * 4.2.2指定ID的住院患者基本信息
     */
    @Override
    public String getPatientInfoByPatientId(Map<String, Object> reqMap) throws Exception {

        isNUll(reqMap, "para");
        Map<String, Object> parmMap = (Map<String, Object>) reqMap.get("para");

        Map<String, Object> patientMap = ccisMapper.getPatientInfoByPatientId(parmMap);

        Map<String, Object> resMap = new HashMap<>();
        resMap.put("patient", patientMap);
        resMap.put("status", 200);
        resMap.put("msg", "成功");

        return XmlMapUtils.formatXml(XmlMapUtils.map2xml(resMap, "response"));
    }

    /**
     * 4.2.3指定ID的住院患者流向信息
     */
    @Override
    public String getPatientFlowInfoByPatientId(Map<String, Object> reqMap) throws Exception {

        isNUll(reqMap, "para");
        Map<String, Object> parmMap = (Map<String, Object>) reqMap.get("para");

        List<Map<String, Object>> itemList = ccisMapper.getPatientFlowInfoByPatientId(parmMap);

        Map<Object, Object> itemsMap = new HashMap<>();
        itemsMap.put("item", itemList);

        Map<String, Object> resMap = new HashMap<>();
        resMap.put("itemList", itemsMap);
        resMap.put("status", 200);
        resMap.put("msg", "成功");

        return XmlMapUtils.formatXml(XmlMapUtils.map2xml(resMap, "response"));
    }

    /**
     * 4.3.1指定ID的住院患者ICU医嘱
     */
    @Override
    public String getAdviceByPatientId(Map<String, Object> reqMap) throws Exception {
        isNUll(reqMap, "para");
        Map<String, Object> parmMap = (Map<String, Object>) reqMap.get("para");

        List<Map<String, Object>> orderList = ccisMapper.getAdviceByPatientId(parmMap);

        Map<String, Object> resMap = new HashMap<>();
        Map<String, Object> orderMap = new HashMap<>();

        orderMap.put("order", orderList);
        resMap.put("orderList", orderMap);
        resMap.put("status", 200);
        resMap.put("msg", "成功");

        return XmlMapUtils.formatXml(XmlMapUtils.map2xml(resMap, "response"));
    }

    /**
     * 进入:4.3.2执行记录
     */
    @Override
    public String getExecuteRecord(Map<String, Object> reqMap) throws Exception {
        isNUll(reqMap, "para");
        Map<String, Object> parmMap = (Map<String, Object>) reqMap.get("para");

        List<Map<String, Object>> orderList = ccisMapper.getExecuteRecord(parmMap);

        Map<String, Object> resMap = new HashMap<>();
        Map<String, Object> orderMap = new HashMap<>();

        orderMap.put("OrderInfo", orderList);
        resMap.put("OrderList", orderMap);
        resMap.put("status", 200);
        resMap.put("msg", "成功");

        return XmlMapUtils.formatXml(XmlMapUtils.map2xml(resMap, "response"));
    }

    /**
     * 4.4.1指定ID的检验报告
     */
    @Override
    public String getLabReportByPatientId(Map<String, Object> reqMap) throws Exception {
        isNUll(reqMap, "para");
        Map<String, Object> parmMap = (Map<String, Object>) reqMap.get("para");

        List<Map<String, Object>> reportList = ccisMapper.getLabReportByPatientId(parmMap);

        for (Map<String, Object> map : reportList) {
            List<Map<String, Object>> contentList = ccisMapper.getReportListContentList(map);
            //提供不了微生物直接去掉节点sensitivityList
           /* for (Map<String, Object> contentMap : contentList) {
                List<Map<String, Object>>  sensitivityList = ccisMapper.getReportListContentListSensitivityList(contentMap);
                Map<String, Object> content = new HashMap<>();
                content.put("Sensitivity",sensitivityList);
                contentMap.put("SensitivityList",content);
            }*/

            Map<String, Object> contentMap = new HashMap<>();
            contentMap.put("Content", contentList);
            map.put("ContentList", contentMap);
        }

        Map<String, Object> resMap = new HashMap<>();
        Map<String, Object> reportInfoMap = new HashMap<>();

        reportInfoMap.put("ReportInfo", reportList);
        resMap.put("ReportList", reportInfoMap);
        resMap.put("status", 200);
        resMap.put("msg", "成功");

        return XmlMapUtils.formatXml(XmlMapUtils.map2xml(resMap, "response"));
    }


    /**
     * 4.4.2指定ID的检查报告
     */
    @Override
    public String getSpecialReportByPatientId(Map<String, Object> reqMap) throws Exception {
        isNUll(reqMap, "para");
        Map<String, Object> parmMap = (Map<String, Object>) reqMap.get("para");

        List<Map<String, Object>> pacsReportList = ccisMapper.getSpecialReportByPatientId(parmMap);

        Map<String, Object> resMap = new HashMap<>();
        Map<String, Object> reportInfoMap = new HashMap<>();

        reportInfoMap.put("report", pacsReportList);
        resMap.put("report_list", reportInfoMap);
        resMap.put("status", 200);
        resMap.put("msg", "成功");

        return XmlMapUtils.formatXml(XmlMapUtils.map2xml(resMap, "response"));
    }


    /*获取住院患者病历信息*/
    @Override
    public String get_Bl_MedicalRecord(Map<String, Object> reqMap) throws Exception {
        isNUll(reqMap, "para");
        Map<String, Object> parmMap = (Map<String, Object>) reqMap.get("para");
        isNUll(parmMap, "PATIENT_ID");
        List<Map<String, Object>> blMedicalRecordList = ccisMapper.get_Bl_MedicalRecord(parmMap);

        logger.info("获取患者[{}]病历信息:{}",parmMap.get("PATIENT_ID"),blMedicalRecordList.size());
        if (!CollectionUtils.isEmpty(blMedicalRecordList)) {
            blMedicalRecordList.stream().forEach(blMedicalRecord -> {
                Object clobObj = blMedicalRecord.get("BL_CLOB");
                if (clobObj instanceof Clob) {
                    String clobStr = ClobToString((Clob) clobObj);
                    blMedicalRecord.put("BL_CLOB_STR", clobStr);
                }
            });
        }
        logger.info("病历结构信息转换成功");
        Map<String, Object> resMap = new HashMap<>();
        Map<String, Object> reportInfoMap = new HashMap<>();
        reportInfoMap.put("bl", blMedicalRecordList);
        resMap.put("bl_list", reportInfoMap);
        resMap.put("status", 200);
        resMap.put("msg", "成功");
        logger.info("获取病历返回成功!");
        return XmlMapUtils.formatXml(XmlMapUtils.map2xml(resMap, "response"));
    }

    /*保存体温单
    * "CJH",	采集号
"CJZH",采集组号
"XMH",	项目号
"JHBZ",计划标志
"CJSJ",采集时间
"ZYH",住院号
"BRKS",	病人科室
"BRBQ",	病人病区
"BRCH",病人床号
"TZNR",	生命体征内容
"FCBZ",	复测标志
"TWDXS",	体温单显示
"JLSJ",记录时间
"JLGH",记录人员
"ZFBZ",作废标志
"YCBZ"异常标志
    *
    * */
    @MultiDataSourceTransactional(transactionManagers = {"hisTransactionManager"})
    @Override
    public String saveFeverRecords(Map<String, Object> reqMap) throws Exception {
        isNUll(reqMap, "para");
        Map<String, Object> parmMap = (Map<String, Object>) reqMap.get("para");
        isNUll(parmMap, Arrays.asList("feverList"));

        List<Map<String,Object>> feverList= (List<Map<String, Object>>) parmMap.get("feverList");

        String zyh = feverList.get(0).get("ZYH").toString();
        Map<String,Object>  zyInfoMap= ccisMapper.getZyInfo(zyh);

        if (ObjectUtils.isEmpty(zyInfoMap)) throw new CommonException("根据住院号["+zyh+"]未获取到患者住院信息!");

        int count=0;
        for (Map<String, Object> feverMap : feverList) {
            isNUll(feverMap, Arrays.asList("XMH","CJSJ","ZYH","TZNR","FCBZ","JLSJ","JLGH","YCBZ"));
            feverMap.put("ZYH",zyInfoMap.get("ZYH"));
            count = ccisMapper.updateSMTZ(feverMap);
            //如果更新的有数据就跳出当前循环
            if (count !=0) continue;
            //BQ_SMTZ_GROUP BQ_SMTZ
            Long cjh = getIdentity("bq", "BQ_SMTZ");
            Long cjzh = getIdentity("bq", "BQ_SMTZ_GROUP");

            Map<String, Object> saveBqSmtzMap = new HashMap<>();
            saveBqSmtzMap.put("CJH",cjh);
            saveBqSmtzMap.put("CJZH",cjzh);
            saveBqSmtzMap.put("XMH",feverMap.get("XMH"));
            saveBqSmtzMap.put("JHBZ","1");
            saveBqSmtzMap.put("CJSJ",feverMap.get("CJSJ"));
            saveBqSmtzMap.put("ZYH",zyInfoMap.get("ZYH"));
            saveBqSmtzMap.put("BRKS",zyInfoMap.get("BRKS"));
            saveBqSmtzMap.put("BRBQ",zyInfoMap.get("BRBQ"));
            saveBqSmtzMap.put("BRCH",zyInfoMap.get("BRCH"));
            saveBqSmtzMap.put("TZNR",feverMap.get("TZNR"));
            saveBqSmtzMap.put("FCBZ",feverMap.get("FCBZ"));
            saveBqSmtzMap.put("TWDXS",feverMap.get("TWDXS"));
            saveBqSmtzMap.put("JLSJ",feverMap.get("JLSJ"));
            saveBqSmtzMap.put("JLGH",feverMap.get("JLGH"));
            saveBqSmtzMap.put("ZFBZ",feverMap.get("ZFPB"));
            saveBqSmtzMap.put("YCBZ",feverMap.get("YCBZ"));
            saveBqSmtzMap.put("XMXB",feverMap.get("XMXB"));
            count = ccisMapper.saveSMTZ(saveBqSmtzMap);
            if (count == 0) throw new CommonException("保存体温单报错,请重试!");
        }
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("status", 200);
        resMap.put("msg", "成功");
        Document response = XmlMapUtils.map2xml(resMap, "response");
        logger.info("返回参数1;{}",response);
        String res = XmlMapUtils.formatXml(response);
        logger.info("返回参数3;{}",res);
        return res;
    }
}
